package DAOJPA;

import java.util.List;

import javax.persistence.Query;

import personne.Personne;
import DAO.DAO;
import DAO.DAOFilm;
import film.Film;

public class DAOFilmJPA extends DAO implements DAOFilm{

	static private DAOFilmJPA instance = null;
	
	private DAOFilmJPA() {
	}
		static public DAOFilm getInstance() {
		 	if (instance == null)
				instance = new DAOFilmJPA();
			 	
		 	return instance;
	}
	
	
	@Override
	public Film getFilm(int code) {
		// TODO Auto-generated method stub
		//Film film = DAO.getManager().find(Film.class, code);
		//return film;
		return DAO.getManager().createQuery("SELECT a FROM Film a WHERE a.code_film = :code",Film.class).setParameter("code", code).getSingleResult();


	}
	

	@Override
	public List<Film> loadAll() {
		// TODO Auto-generated method stub
		return DAO.getManager().createQuery("SELECT a FROM Film a WHERE a.valide = :vrai",Film.class).setParameter("vrai", 0).getResultList();

	}

	@Override
	public List<Film> loadAllFilmInvalide() {
		// TODO Auto-generated method stub
		return DAO.getManager().createQuery("SELECT a FROM Film a WHERE a.valide = :vrai",Film.class).setParameter("vrai", 1).getResultList();

	}
	
	
	@Override
	public int getNombreFilm() {
		// TODO Auto-generated method stub
		return this.loadAll().size();
	}

	@Override
	public void save(Film a) {
		// TODO Auto-generated method stub
		
			DAO.getManager().persist(a);
			DAO.commit();
			
	}

	@Override
	public void delete(Film a) {
		// TODO Auto-generated method stub
		getManager().remove(a);
		DAO.commit();
	}

	@Override
	public void deleteFromId(int code)
	{
		
		DAO.getManager().createQuery("DELETE FROM Film a WHERE a.code_film = :code AND a.valide = :vrai" , Film.class).setParameter("code", code).setParameter("vrai", 0).executeUpdate();
		DAO.commit();
	}
	
	@Override
	public void deleteFilmQuery(Film a)
	{

		Query query = DAO.getManager().createQuery("DELETE FROM Film a WHERE a.code_film = :p1 AND a.titre = :p2 AND a.annee_sortie = :p3 AND a.cout = :p4 AND a.genre = :p5 AND a.lien_photo = :p6 AND a.valide = :p7 AND a.date_creation = :p8" , Film.class);
		query.setParameter("p1", a.getCode_film()).setParameter("p2", a.getTitre()).setParameter("p3", a.getAnnee_sortie()).setParameter("p4", a.getCout()).setParameter("p5", a.getGenre()).setParameter("p6", a.getLien_photo()).setParameter("p7", a.getValide()).setParameter("p8", a.getDate_creation()).executeUpdate();
		DAO.commit();
	}
	
	
	public List<Film> getFilmTitre(String  chaine)
	{
		return DAO.getManager().createQuery("SELECT a FROM Film a WHERE a.valide = :vrai AND a.titre LIKE :chaine ",Film.class).setParameter("vrai", 0).setParameter("chaine", "%"+chaine+"%").getResultList();
	}
	
}
